<template>
  <div class="detail-container">
    <el-form
      ref="postForm"
      :rules="rules"
      :model="postForm" 
      label-width="85px" 
      label-position="right"
      v-loading="fetchLoading"
    >
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="postForm.name" placeholder="请填写角色名称"></el-input>
      </el-form-item>
      <el-form-item label="权限菜单" prop="auth_ids">
        <el-input v-model="postForm.auth_ids" v-show="showTreeInput" disabled></el-input>
        <el-tree 
          ref="tree"
          :data="authList" 
          :props="defaultProps" 
          :check-strictly="checkStrictly"
          show-checkbox
          node-key="id"
          default-expand-all 
          @check-change="onTreeChange"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary" 
          :loading="saveLoading"
          @click.native.prevent="handleSave"
        >{{ update ? '确认更新' : '确认新增' }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { roleInfo, roleCreate, roleUpdate } from '@/api/role'
import { authList } from '@/api/auth'
import { int2Bool } from '@/utils/util'

const defaultForm = {
  name: '',
  auth_ids: '',
  is_super: 0,
}
export default {
  name: 'RoleDetail',
  props: {
    update: { // 是否编辑
      type: Boolean,
      default: false,
    },
    id: [String, Number], // 文章id 编辑时传递
  },
  data() {
    return {
      authList: [],
      postForm: {},
      fetchLoading: false,
      saveLoading: false,
      rules: {
        name: [{ required: true, message: "角色名称为必填", trigger: "blur" }],
        auth_ids: [{ required: true, message: "权限菜单为必选", trigger: "blur" }],
      },
      defaultProps: {
        children: 'children',
        label: 'menu_title',
      },
      checkStrictly: this.update,
      showTreeInput: process.env.NODE_ENV === 'development'
    }
  },
  created() {
    if (this.update) {
      this.getRoleInfo()
    } else {
      this.postForm = Object.assign({}, defaultForm)
    }
    this.getAuthList()
  },
  methods: {
    // 权限列表
    async getAuthList() {
      const { data } = await authList()
      this.authList = this.status2Bool(data)
    },
    // 递归将 status 转为 bool 值
    status2Bool(auths) {
      return auths.map(auth => {
        auth.disabled = !int2Bool(auth.status)
        if (auth.children && auth.children.length) {
          this.status2Bool(auth.children)
        }
        return auth
      })
    },
    // 角色详情
    async getRoleInfo() {
      try {
        this.fetchLoading = true
        const { info } = await roleInfo(this.id)
        this.postForm = info
        this.setCheckedKeys(info.auth_ids)
      } finally {
        this.fetchLoading = false
      }
    },
    // 设置权限菜单选中
    setCheckedKeys(strAuthIds) {
      const authIds = strAuthIds.split(',')
      this.$refs.tree.setCheckedKeys(authIds)
      this.checkStrictly = false
    },
    // 选中状态改变 存储权限菜单id
    onTreeChange() {
      const tree = this.$refs.tree
      const checkedIds = tree.getCheckedKeys()
      const halfCheckedIds = tree.getHalfCheckedKeys()
      const allCheckedIds = checkedIds.concat(halfCheckedIds).sort()
      this.postForm.auth_ids = allCheckedIds.join(',')
    },
    // 保存、修改
    handleSave() {
      this.$refs.postForm.validate(async valid => {
        if (!valid) return
        try {
          this.saveLoading = true
          if (this.update) {
            await roleUpdate(this.postForm)
            this.$notify.success({
              title: '成功',
              message: '更新成功',
              duration: 3000,
            });
            this.$router.go(-1)
          } else {
            await roleCreate(this.postForm)
            this.$notify.success({
              title: '成功',
              message: '新增成功',
              duration: 3000,
            });
            this.$refs.postForm.resetFields()
            this.$refs.tree.setCheckedKeys([])
          }
        } finally {
          this.saveLoading = false
        }
      })
    }
  },
}
</script>

<style lang="scss" scoped>

</style>